package com.hcm;

import java.io.IOException;
import java.util.*;
import javax.servlet.http.*;
import javax.jdo.Query;
import com.hcm.common.ClientBean;
import com.hcm.common.Utility;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.amazonaws.mturk.service.axis.*;
import com.amazonaws.mturk.service.exception.ServiceException;
import com.amazonaws.mturk.util.*;
//import com.amazonaws.mturk.requester.HIT;

@SuppressWarnings("serial")
public class DemoServlet  extends BaseServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		
		resp.setContentType("text/plain");
		
		String action = req.getParameter("a");
		
		if(Utility.IsStringNullOrEmpty(action))
		{
			resp.getWriter().println("No action!");
		}
		else{
			if (action.equals("i")){
				// Initialize object and Save to DB
				ClientBean cb = new ClientBean("Client2", "new Client2");
			
				try
				{
					pm.makePersistent(cb);
					resp.getWriter().println(cb.getClientID());
				}
				finally
				{
					//pm.close();
				}
			}else if(action.equals("l")){
				// load data by ClientName from DB and display
				Query q = pm.newQuery(ClientBean.class);
				q.setFilter("clientName == cName");
				q.declareParameters("String cName");
			
				try
				{
					//Key k = KeyFactory.createKey(ClientBean.class.getSimpleName(), "Client2"); 
					@SuppressWarnings("unchecked")
					List<ClientBean> results = (List<ClientBean>)q.execute(req.getParameter("c"));
					if ((null != results) && (1 <= results.size()))
					{
						resp.getWriter().println(results.get(0).getClientName());
					}
				}
				finally
				{}
			}else if(action.equals("lk")){
				// load data by key from DB and display
							
				try
				{
					Key k = KeyFactory.createKey(ClientBean.class.getSimpleName(), 2); 
					
					ClientBean results = pm.getObjectById(ClientBean.class, k);
				
					resp.getWriter().println(results.getClientName());
				}
				finally
				{}
			}else{
				ClientConfig cc = new ClientConfig();
				cc.setAccessKeyId(Utility.AccessKey);
				cc.setSecretAccessKey(Utility.SecretKey);
				cc.setRetryAttempts(3);
				cc.setRetryDelayMillis(500);
				try
				{
					HCMRequesterService service = new HCMRequesterService(cc); 

					resp.getWriter().println(service.getAccountBalance());
				}
				catch(ServiceException ex)
				{
					resp.getWriter().println(ex.getMessage());
				}
			}
		}
		
		//resp.getWriter().println("Hello, world");
		
		/*
		PropertiesClientConfig pcConfig = new PropertiesClientConfig();
		pcConfig.setAccessKeyId(Utility.AccessKey);
		pcConfig.setSecretAccessKey(Utility.SecretKey);
		pcConfig.setServiceURL(Utility.ServiceURLSandbox);
		*/
		//RequesterService service = new RequesterService(pcConfig); 
		
	}
}
